package pikes.peak;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import pikes.ecma.FunctionCall;
import pikes.ecma.IndexedAccess;
import pikes.ecma.MemberPropertyAccess;
import pikes.ecma.SourceElements;
import pikes.html.xhtml.Flow;
import pikes.html.xhtml.form.Input;
import pikes.peak.InputText;
import pikes.peak.RequestProperty;
import pikes.peak.test.AssertHtml;
import pikes.peak.test.PikesPeakComponentTestCase;

import org.springframework.web.servlet.support.RequestContext;

public class InputTextTestCase extends PikesPeakComponentTestCase {

	@Test
	public void defineEmptyInputText() throws Exception {
		InputText inputText = new InputText();

		Input expected = new Input(Input.InputType.TEXT);

		Flow actual = inputText.createHtml(new HashMap(), pikesPeakRequest.getRequestContext());
		AssertHtml.assertEquals(expected, actual);
	}

	@Test
	public void defineEmptyInputTextWithName() throws Exception {
		InputText inputText = new InputText("name");

		Input expected = new Input("name", Input.InputType.TEXT);

		Flow actual = inputText.createHtml(new HashMap(), pikesPeakRequest.getRequestContext());
		AssertHtml.assertEquals(expected, actual);
	}

	@Test
	public void defineInputTextWithValueProviderWithNullValue() throws Exception {
		InputText inputText = new InputText(new RequestProperty<CharSequence>() {

			public CharSequence getValue(Map model, RequestContext requestContext) throws Exception {
				return null;
			}

		});

		Input expected = new Input(Input.InputType.TEXT);

		Flow actual = inputText.createHtml(new HashMap(), pikesPeakRequest.getRequestContext());
		AssertHtml.assertEquals(expected, actual);
	}

	@Test
	public void defineInputTextWithValueProviderWithNonNullValue() throws Exception {
		InputText inputText = new InputText(new RequestProperty<CharSequence>() {

			public CharSequence getValue(Map model, RequestContext requestContext) throws Exception {
				return "value";
			}

		});

		Input expected = new Input(Input.InputType.TEXT, "value");

		Flow actual = inputText.createHtml(new HashMap(), pikesPeakRequest.getRequestContext());
		AssertHtml.assertEquals(expected, actual);
	}

	@Test
	public void defineEmptyInputTextWithOnChange() throws Exception {
		InputText cb = new InputText();

		SourceElements elements = new SourceElements();
		elements.add(new FunctionCall(new MemberPropertyAccess(new IndexedAccess(new MemberPropertyAccess("document",
				"forms"), "0"), "submit")));

		cb.setOnChange(elements);

		Input expected = new Input(Input.InputType.TEXT);
		expected.setOnChange("document.forms[0].submit();");

		Flow actual = cb.createHtml(new HashMap(), pikesPeakRequest.getRequestContext());
		AssertHtml.assertEquals(expected, actual);
	}
}
